<template>
  <div>
    <div id="list-item" ref="form">
      <el-form :inline="true">
        <el-form-item>
          <el-date-picker
              v-model="query.createDate"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="选择日期"
              clearable>
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-input placeholder="请输入电话" clearable v-model="query.phone" @keyup.enter.native="onConfirm">
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-input placeholder="请输入备注" clearable v-model="query.info" @keyup.enter.native="onConfirm">
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onConfirm">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" @click="onClear">清空</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table ref="table" :data="tableData" :max-height="maxTableHeight" border style="width: 100%" v-loading="loading">
      <el-table-column type="index" width="50">
      </el-table-column>
      <el-table-column label="时间" width="160">
        <template slot-scope="{row}">
          <span>{{ row.create_time| dateFormat('yyyy-MM-dd hh:mm:ss') }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="电话" width="80">
      </el-table-column>
      <el-table-column prop="dept_name" label="科室" width="130">
      </el-table-column>
      <el-table-column prop="ip" label="IP地址" width="100">
      </el-table-column>
      <el-table-column prop="info" label="备注">
      </el-table-column>
      <el-table-column prop="real_name" label="录入人" width="80">
      </el-table-column>
      <el-table-column prop="status" sortable label="状态" width="80">
        <template slot-scope="{row}">
          <el-tag :type="statusMap[row.status].type">
            {{ statusMap[row.status].description }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
              @click.native.prevent="handleConnect(scope.row.ip)"
              size="small"
              v-if="scope.row.ip !== ''">
            联机
          </el-button>
          <el-button
              @click.native.prevent="handleFinish(scope.row)"
              type="success"
              size="small"
              v-if="scope.row.status === '0'">
            完成
          </el-button>
          <el-button
              @click.native.prevent="handleUpdate(scope.row, scope.$index)"
              type="primary"
              size="small">
            修改
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="编辑" :visible.sync="dialogFormVisible">
      <!--          :rules="rules" 自定义验证规则-->
      <el-form
          ref="dataForm"
          :model="temp"
          label-position="left"
          label-width="120px"
          style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="电话：" prop="phone">
          <el-input v-model="temp.phone" @keyup.enter.native="updateData"/>
        </el-form-item>
        <el-form-item label="IP地址：" prop="ip">
          <el-input v-model="temp.ip" @keyup.enter.native="updateData"/>
        </el-form-item>
        <el-form-item label="备注：" prop="info">
          <el-input v-model="temp.info" @keyup.enter.native="updateData"/>
        </el-form-item>
        <el-form-item label="状态：" prop="status">
          <el-select v-model="temp.status" class="filter-item" placeholder="请选择状态">
            <el-option key="'0'" label="未完成" :value="'0'" />
            <el-option key="'1'" label="已完成" :value="'1'" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="updateData">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { parseTime } from '@/utils'

export default {
  name: 'search-page',
  mounted () {
    setTimeout(() => {
      this.maxTableHeight = window.innerHeight - this.$refs.form.offsetHeight - 20
    }, 0)
    let that = this
    window.onresize = () => {
      return (() => {
        that.maxTableHeight = window.innerHeight - that.$refs.form.offsetHeight - 20
      })()
    }
  },
  created () {
    // 初始化时加载当日数据
    // 获取当日零点时间
    const startTimeStamp = new Date(new Date().toLocaleDateString()).getTime()
    this.loading = true
    var self = this
    this.$pool.query('select a.*,(select real_name from user b where b.user_id=a.submit_user_id) real_name from record a where create_time>? order by a.create_time desc', [startTimeStamp], function (err, rows) {
      if (!err) {
        self.tableData = JSON.parse(JSON.stringify(rows))
      }
      console.log(err)
      self.loading = false
    })
  },
  data () {
    return {
      maxTableHeight: 0,
      tableData: [],
      loading: false,
      statusMap: [
        {
          description: '未完成',
          type: 'info'
        },
        {
          description: '已完成',
          type: 'success'
        }
      ],
      dialogFormVisible: false,
      temp: {
        id: '',
        phone: '',
        ip: '',
        info: '',
        status: undefined,
        create_time: undefined,
        update_time: undefined
      },
      query: {
        createDate: parseTime(new Date(), '{y}-{m}-{d}'),
        phone: '',
        info: ''
      }
    }
  },
  filters: {
    dateFormat (date, fmt) {
      date = new Date(date)
      let o = {
        'M+': date.getMonth() + 1, // 月份
        'd+': date.getDate(), // 日
        'h+': date.getHours(), // 小时
        'm+': date.getMinutes(), // 分
        's+': date.getSeconds(), // 秒
        'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
        'S': date.getMilliseconds() // 毫秒
      }
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
      }
      for (let k in o) {
        if (new RegExp('(' + k + ')').test(fmt)) {
          fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
        }
      }
      return fmt
    }

  },
  methods: {
    searchInDB (query) {
      // 保存到数据库
      let params = []
      if (query.createDate) {
        params.push(` FROM_UNIXTIME(substr(create_time, 1, 10),"%Y-%m-%d")= "${query.createDate}"`)
      }
      if (query.info) {
        params.push(` info like "%${query.info}%" `)
      }
      if (query.phone) {
        params.push(` phone = "${query.phone}" `)
      }
      let paramsValue = params.join(' and ')
      if (paramsValue) {
        paramsValue = ' where ' + paramsValue
      }
      // TODO 分页
      var sql = `select a.*,(select real_name from user b where b.user_id=a.submit_user_id) real_name from record a ${paramsValue} order by a.create_time desc`
      this.loading = true
      var self = this
      this.$pool.query(sql, function (err, rows) {
        if (err) {
          console.log(err)
        }
        self.tableData = JSON.parse(JSON.stringify(rows))
        self.loading = false
      })
    },
    isValidIp (ip) {
      return /^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$/.test(ip)
    },
    resetForm () {
      this.query = {
        createDate: undefined
      }
    },
    onConfirm () {
      // 备注和电话必须有一项
      if (!this.query.createDate) {
        // this.$message.error({
        //   message: '请填入日期',
        //   duration: 800
        // })
        // return
      }
      this.searchInDB(this.query)
    },
    onClear () {
      this.resetForm()
    },
    handleFinish (row) {
      let recordId = row.record_id
      this.$pool.query('update record set status=?, update_time=? where record_id=?', ['1', new Date().getTime(), recordId], function (err, result) {
        if (!err) {
          console.log(result)
        }
        console.log(err)
      })
      row.status = '1'
    },
    handleUpdate (row, index) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.index = index
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData () {
      let self = this
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (this.temp.ip) {
            if (!this.isValidIp(this.temp.ip)) {
              this.$message.error({
                message: 'IP地址格式错误，请重新输入',
                duration: 800
              })
              return
            }
          }
          let updateSql = 'update record set phone=?, info=?, status=?, ip=?, update_time=? where record_id=?'
          let params = [this.temp.phone, this.temp.info, this.temp.status, this.temp.ip, new Date().getTime(), this.temp.record_id]
          this.$pool.query(updateSql, params, function (err, result) {
            if (!err) {
              console.log(self.temp)
              self.$set(self.tableData, self.temp.index, self.temp)
            }
          })
          this.dialogFormVisible = false
          this.$notify({
            title: '操作成功',
            message: '修改信息成功',
            type: 'success',
            duration: 2000
          })
        }
      })
    },
    handleConnect (ip) {
      // radmin联机
      console.log('联机中...')

      // TODO 可以配置修改exe所在路径
      const exePath = 'C:\\Program Files (x86)\\Radmin Viewer 3\\Radmin.exe'
      const defaultPort = '8020'
      // 路径带空格时需要加上start ""
      const command = `start "" "${exePath}" /connect:${ip}:${defaultPort} /fullscreen`
      console.log(command)
      this.$cmd.run(command)
    }
  }
}
</script>

<style>
/* CSS */
.el-table {
  width: 99.9% !important;
}
</style>
